package com.asymptote.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.asymptote.Constant;
import com.asymptote.mid.Member;

public class MemberServlet extends HttpServlet {
	private static final long serialVersionUID = -8509931051570843997L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		doGet(request, response);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		
		String url = "/register.jsp";
		int index = -1;
		try {
			index = Integer.parseInt( request.getParameter("act") );
		} catch(NumberFormatException nfe) {
			index = Constant.Action.RenderInterface;
		}
		switch ( index ) {
		case Constant.Action.RenderInterface:
			url = "/register.jsp";
			renderInterface( request );
			break;
		case Constant.Action.AddEntity:
			url = "/member.do?act=" + Constant.Action.RenderInterface;
			addMember( request );
			break;
		}
		RequestDispatcher dispatcher = request.getRequestDispatcher( url );
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private void renderInterface(HttpServletRequest request) {
		List<Member> members = Member.getAll();
		request.setAttribute( "members", members );
		request.setAttribute( "act", Constant.Action.AddEntity );
	}
	private void addMember(HttpServletRequest request) {
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String gdr = request.getParameter("gender");
		String idNum = request.getParameter("idnum");
		String mobile = request.getParameter("mobile");
		String email = request.getParameter("email");
		String desc = request.getParameter("desc");		

		boolean gender = ( gdr.equals("1") ) ? true : false;
		
		Member m = new Member();
		m.setName(name);
		m.setPassword(password);
		m.setGender(gender);
		m.setIdNum(idNum);
		m.setMobile(mobile);
		m.setEmail(email);
		m.setDesc(desc);
		m.save();
	}
}
